/* pipcreate.c - pipcreate, pipnewid */

#include <xinu.h>
#include <mips.h>

static  pipid32   pipnewid(void);

/*------------------------------------------------------------------------
 *  pipcreate, pipnewid  -  Create a pipe
 *------------------------------------------------------------------------
 */

pipid32 pipcreate(void)
{
	intmask mask;                   /* saved interrupt mask         */
	pipid32 pipid;			/* ID of newly created pipe	*/
	struct pipent *piptr;		/* ptr to pipe's table entry	*/

	mask = disable();		/* saved interrupt mask         */

	pipid = pipnewid();
	
	if (isbadpipid(pipid) || (piptr->pistate != PIPE_FREE)) {
                restore(mask);
                return (pipid32)SYSERR;
        }
	
	piptr = &piptab[pipid];
	piptr->pistate = PIPE_USED;
	
	uint32  j;			/* iterate through all buffer slots	*/

	for (j = 0; j < PIPE_SIZ; j++) {	/* initialize the buffer	*/
                piptr->pipebuffer[j] = ' ';
	}

	//piptr->psem = semcreate(PIPE_SIZ);	/* initialize producer sem	*/
	//piptr->csem = semcreate(0);		/* initialize consumer sem	*/

	restore(mask);
	return pipid;
}

/*------------------------------------------------------------------------
 *  pipnewid  -  Obtain a new (free) pipe ID
 *------------------------------------------------------------------------
 */
local   pipid32   pipnewid(void)
{
        uint32  i;                      /* iterate through all pipes*/
        static  pipid32 nextpipid = 1;	/* position in table to try or  */
                                        /*  one beyond end of table     */

        /* Check all NPIPE slots */

        for (i = 0; i < NPIPE; i++) {
                nextpipid %= NPIPE;       /* wrap around to beginning */
                if (piptab[nextpipid].pistate == PIPE_FREE) {
                        return nextpipid++;
                } else {
                        nextpipid++;
                }
        }
        return (pipid32) SYSERR;
}
